package com.java.comprehensive.design.building_modelling.abstract_factory_pattern.config_factory;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class CoffeeFactory {


    //1. 定义容器存储对象
    private static Map<String, Coffee> map = new HashMap<>();

    //2. 加载配置文件，创建全类名对象
    static {
        //2.1 创建配置文件对象
        Properties properties = new Properties();
        //2.2 加载配置文件的内容
        InputStream is = CoffeeFactory.class.getClassLoader().getResourceAsStream("bean.properties");
        try {
            properties.load(is);
            for (Object key : properties.keySet()) {
                String className = properties.getProperty((String) key);

                //反射创建对象
                Class<?> aClass = Class.forName(className);
                Coffee o = (Coffee) aClass.newInstance();
                map.put((String) key, o);
            }
        } catch (IOException | ClassNotFoundException | InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }

    }

    public static Coffee createCoffee(String coffeeName) {
        return map.get(coffeeName);
    }
}
